package cn.codehaus.core.common.server;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.codehaus.core.common.Constants;

/**
 * SpringBwan加载器<br>
 * (1)、使用此加载器可以获得一个Spring容器的ApplicationContext实例,通过此实例你就可以方便的使用getBean()
 * 方法获取SpringBean.<br>
 * (2)、您也可以直接通过我们提供的getSpringBean()方法活得SpringBean。
 * 
 * @author XiongChun
 * @since 2009-07-22
 */
public class ApplicationContextUtil implements ApplicationContextAware{
	
	private static Log log = LogFactory.getLog(ApplicationContextUtil.class);
	
	private static ApplicationContext applicationContext;

	/**
	 * 返回ApplicationContext对象
	 * 
	 * @return ApplicationContext 返回的ApplicationContext实例
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 实现ApplicationContextAware接口的回调方法,设置上下文环境
	 */
	@SuppressWarnings("static-access")
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		 this.applicationContext = applicationContext;
	}
	/**
	* 获取对象
	* 
	* @param name
	* @return Object bean的实例
	* @throws BeansException
	*/
	public static Object getBean(String beanName) throws BeansException {
	   if (!ApplicationContextUtil.containsBean(beanName)) {
	    return null;
	   } else {
	    return applicationContext.getBean(beanName);
	   }
	}
	/**
	* 获取类型为requiredType的对象
	* 如果bean不能被类型转换，相应的异常将会被抛出（BeanNotOfRequiredTypeException）
	* 
	* @param name
	*            bean注册名
	* @param requiredType
	*            返回对象类型
	* @return Object 返回requiredType类型对象
	* @throws BeansException
	*/
	@SuppressWarnings("unchecked")
	public static Object getBean(String name, Class requiredType)
	    throws BeansException {
	   return applicationContext.getBean(name, requiredType);
	}
	/**
	* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
	* 
	* @param name
	* @return boolean
	*/
	public static boolean containsBean(String name) {
	   return applicationContext.containsBean(name);
	}
}
